package com.aizuda.boot.modules.business.employee.controller;

import com.aizuda.boot.modules.business.employee.domain.request.EmployeeQueryVO;
import com.aizuda.boot.modules.business.employee.domain.request.EmployeeQueryById;
import com.aizuda.boot.modules.business.employee.domain.request.EmployeeQueryWithContractVO;
import com.aizuda.boot.modules.business.employee.domain.request.GetEmployeeIdsByDeptDTO;
import com.aizuda.boot.modules.business.employee.domain.request.SearchEmployeeByNameDTO;
import com.aizuda.boot.modules.business.employee.domain.response.EmployeeQueryShowVO;
import com.aizuda.boot.modules.business.employee.domain.response.EmployeeQueryWithParticipantVO;
import com.aizuda.boot.modules.business.employee.domain.response.EmployeeSearchResultVO;
import com.aizuda.boot.modules.business.employee.domain.response.LoginCheckVO;
import com.aizuda.boot.modules.business.employee.provider.EmployeeProvider;
import com.aizuda.boot.modules.business.permission.domain.response.EmployeeShowVO;
import com.aizuda.boot.modules.business.employee.mapper.EmployeeMapper;
import com.aizuda.boot.modules.business.department.domain.response.DepartmentInfoDTO;
import com.aizuda.boot.modules.business.department.service.DepartmentService;
import com.aizuda.boot.modules.system.entity.SysUser;
import com.aizuda.boot.modules.system.service.ISysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author duanyao
 * @date 2022/12/05 15:07
 * @description: 用户管理
 */
@RequestMapping("/employee")
@RestController
@Validated
@Slf4j
@Tag(name = "用户管理", description = "员工相关接口")
public class EmployeeController {
    @Resource
    private EmployeeProvider employeeProvider;
    @Resource
    private EmployeeMapper employeeMapper;
    @Resource
    private ISysUserService sysUserService;
    @Resource
    private DepartmentService departmentService;

    @GetMapping("/getUserById/{employeeId}")
    @Operation(summary = "根据用户id查询用户信息", description = "feign调用，非前端调用")
    public LoginCheckVO getUserById(@PathVariable Long employeeId) {
        SysUser employee = sysUserService.getOne(
                new LambdaQueryWrapper<SysUser>()
                        .eq(SysUser::getId, employeeId)
                        .eq(SysUser::getDeleted, false)
        );
        LoginCheckVO loginCheckVO = new LoginCheckVO();
        loginCheckVO.setId(employee.getId());
        loginCheckVO.setName(employee.getNickName());
        loginCheckVO.setAliasName(employee.getRealName());
        loginCheckVO.setMobile(employee.getPhone());
        loginCheckVO.setAvatar(employee.getAvatar());
        loginCheckVO.setEmail(employee.getEmail());
        return loginCheckVO;
    }

    @PostMapping("/getUserByIds")
    @Operation(summary = "根据员工ids获取员工信息")
    public List<EmployeeShowVO> getUserByIds(@RequestBody @Valid List<Long> employeeIds){
        List<EmployeeShowVO> employeeShowVOList = sysUserService.listByIds(employeeIds).stream().map(employee -> {
            EmployeeShowVO employeeShowVO = new EmployeeShowVO();
            employeeShowVO.setId(employee.getId());
            employeeShowVO.setName(employee.getNickName());
            employeeShowVO.setAvatar(employee.getAvatar());
            return employeeShowVO;
        }).collect(Collectors.toList());
        return employeeShowVOList;
    }

    @PostMapping("/queryEmployee")
    @Operation(summary = "查询员工")
    public List<EmployeeQueryShowVO> queryEmployee(@RequestBody @Validated EmployeeQueryVO query) {
        return sysUserService.queryEmployee(query);
    }

    @PostMapping("/queryEmployee/negotiation")
    @Operation(summary = "查询员工并标记协商参与者状态")
    public List<EmployeeQueryWithParticipantVO> queryEmployeeWithNegotiation(@RequestBody @Validated EmployeeQueryWithContractVO query) {
        return sysUserService.queryEmployeeWithNegotiationStatus(query);
    }

    @PostMapping("/searchByName")
    @Operation(summary = "根据姓名关键词模糊搜索员工")
    public List<EmployeeSearchResultVO> searchEmployeesByName(@RequestBody @Valid SearchEmployeeByNameDTO dto) {
        List<EmployeeSearchResultVO> results = employeeMapper.searchEmployeesByName(dto.getKeyword());
        
        // 为每个员工查询主部门信息
        for (EmployeeSearchResultVO result : results) {
            try {
                DepartmentInfoDTO mainDepartment = departmentService.getEmployeeMainDepartment(result.getId());
                if (mainDepartment != null) {
                    result.setMainDepartmentId(mainDepartment.getId());
                    result.setMainDepartmentName(mainDepartment.getName());
                }
            } catch (Exception e) {
                log.error("获取员工[{}]主部门信息失败", result.getId(), e);
                // 如果获取主部门失败，保持原有的null值
            }
        }
        
        return results;
    }

    @PostMapping("/queryEmployeeShow")
    @Operation(summary = "根据id查询用户")
    public List<EmployeeQueryShowVO> queryEmployeeShow(@RequestBody @Validated EmployeeQueryById employeeIds){
        return sysUserService.queryEmployeeShow(employeeIds);
    }


    @GetMapping("/getCurrentUserTenantId/{employeeId}")
    @Operation(summary = "查询当前登录员工权限")
    public Integer getCurrentUserTenantId(@PathVariable Long employeeId){
        return employeeMapper.getTenantId(employeeId);
    }

    @PostMapping("/getEmployeeIdsByDept")
    @Operation(summary = "根据部门ID查询以该部门为主部门的员工ID列表")
    public List<Long> getEmployeeIdsByMainDepartment(@RequestBody @Valid GetEmployeeIdsByDeptDTO dto) {
        List<Long> employeeIds = sysUserService.getEmployeeIdsByMainDepartment(dto.getDepartmentId());
        return employeeIds;
    }
}


